<template>
  <div>
    <el-card class="table-card">
      <div slot="header" class="clearfix">
        <h4>上下限批量维护</h4>
      </div>
      <BasicTable
        isCustomSort
        showPagination
        showActionCol
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="480"
        :actionRender="actionRender"
        :actionColWidth="100"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
        @customSortChange="handleSortTable"
      >
        <el-row slot="content_context" type="flex" justify="space-between">
          <el-form class="reson-form" size="mini" ref="resonForm" :model="resonForm" label-width="75px">
            <el-form-item label="调整原因:">
              <el-input maxlength="200" :rows="1" type="textarea" v-model="resonForm.launchReason"></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-upload
              v-if="showBtn('导入')"
              style="margin-right: 10px; display: inline"
              :disabled="uploadLoading"
              :show-file-list="false"
              accept=".xlsx"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="handleBeforeUpload"
              :action="importUrl"
              :data="uploadParams"
            >
              <el-tooltip>
                <ul slot="content" class="tooltip">
                  <li>导入说明：</li>
                  <li>1.请通过上下限管理导出模板编辑后进行导入数据(表头不要动);</li>
                  <li>2.从表格第二行进行导入数据;</li>
                  <li>3.数据源可以通过上下限查询列表页面根据条件导出获取;</li>
                </ul>
                <el-button
                  @click="handleUploadClick"
                  :loading="uploadLoading"
                  type="primary"
                  size="mini"
                  >导入</el-button
                >
              </el-tooltip>
            </el-upload>
            <el-button
              :disabled="noData"
              :loading="submitLoading"
              type="primary"
              size="mini"
              @click="handleSubmit"
              >提交</el-button
            >
            <el-button
              v-if="pageType == 'add'"
              type="primary"
              size="mini"
              @click="handleGoBack"
              >返回</el-button
            >
          </div>
        </el-row>
      </BasicTable>
      <FooterFields v-if="pageType == 'view'" :footerFields="recordInfoData" />
    </el-card>
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/skusTable';
import skusPage from '@/mixins/commodity/skusPage';
import { EDIT_TABLE_COLUMNS } from '../constants';
import { setAuthBtnId, isResponseSuccess } from '@/utils/bizUtils';
import FooterFields from '@/pages/commodity/components/FooterFields';
import {
  queryRecordLimitDetailDataService,
  submitLimitDataService,
  deleteLimitDataService
} from '@/api/stock/upperLowerLimits';

export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    BasicTable,
    FooterFields
  },
  data () {
    const menuId = sessionStorage.menuId;
    return {
      menuId,
      buttonId: '',
      uploadParams: {},
      recordInfoData: {},
      tableInfo: {
        list: [],
        columns: EDIT_TABLE_COLUMNS,
        loading: false,
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 100 // 当前页码size
      },
      pageSizes: [100, 1000],
      uploadLoading: false,
      submitLoading: false,
      recordNo: '',
      pageType: 'add',
      sortType: 1,
      importUrl: '',
      hasErrorData: false,
      resonForm: {
        launchReason: ''
      }
    }
  },
  computed: {
    noData () {
      return this.tableInfo.list.length === 0;
    },
  },
  mounted () {
    const { type, recordNo, } = this.$route.query
    if (recordNo) {
      this.pageType = type
      this.recordNo = recordNo
      this.getTableData()
    }
  },
  methods: {
    handleUploadClick () {
      setAuthBtnId('导入')
      const url = `${this.uploadBaseURL}sysback/product/limit/importRecord?menuId=${this.menuId}&buttonId=${sessionStorage.buttonId}`
      if (this.pageType == 'add') {
        this.importUrl = url
      }
      if (this.pageType == 'edit') {
        this.importUrl = `${url}&recordNo=${this.recordNo}`
      }
    },
    // 表格排序 1 降序 0 升序
    handleSortTable (data) {
      const { order } = data
      if (order == 'descending') {
        this.sortType = '1';
      } else if (order == 'ascending') {
        this.sortType = '0';
      }
      this.getTableData()
    },
    actionRender (h, { row }) {
      return (
        <div class="table-action">
          <el-button size="mini" type="text" onClick={() => this.handleDelete(row)}>删除</el-button>
        </div>
      );
    },
    // 获取表格数据
    async getTableData () {
      const data = {
        ...this.paginationParams,
        recordNo: this.recordNo,
        sortType: this.sortType,
      };
      setAuthBtnId();
      const res = await queryRecordLimitDetailDataService(data, state => { this.tableInfo.loading = state });
      if (res?.retData) {
        const {
          recordNo,
          commitStateStr,
          pusherName,
          pushTime,
          pusherDeptName,
          pusherAreaName,
          reason,
          productUpdateCommitRecordLimitDetailVoPager,
          hasErrorData,
          launchReason
        } = res.retData;
        this.recordInfoData = {
          recordNo,
          commitStateStr,
          pusherName,
          pushTime,
          pusherDeptName,
          pusherAreaName,
          reason,
        }
        if (!this.resonForm.launchReason) {
          this.resonForm.launchReason = launchReason
        }
        const { totalNum, results } = productUpdateCommitRecordLimitDetailVoPager;
        this.tableInfo.list = results;
        this.total = totalNum;
        this.hasErrorData = hasErrorData;
        if (hasErrorData) {
          this.tableInfo.columns = [
            {
              title: '异常原因',
              key: 'errorMsg',
              width: '130',
              sortable: true,
              errorTip: true,
              notShowTip: true
            },
            ...this.tableInfo.columns.filter(item => item.key !== 'errorMsg')
          ]
        } else {
          this.tableInfo.columns = this.tableInfo.columns.filter(item => item.key !== 'errorMsg')
        }
      } else {
        this.tableInfo.list = [];
        this.total = 0;
      }
    },
    // 删除
    async handleDelete (row) {
      const ids = []
      if (row.id) {
        ids.push(row.id)
      }
      const res = await deleteLimitDataService(ids)
      if (res) {
        this.$message.success('删除成功')
        this.getTableData()
      }
    },
    // 提交
    async handleSubmit () {
      const { launchReason } = this.resonForm
      if (!launchReason) {
        return this.$message.error('请填写调整原因')
      }
      if (this.hasErrorData) {
        return this.$message.error('存在异常原因禁止提交')
      }
      this.submitAction('')
    },
    async submitAction (deleteNoUpdateData) {
      const params = {
        recordNo: this.recordNo,
        launchReason: this.resonForm.launchReason,
        deleteNoUpdateData
      }
      const res = await submitLimitDataService(params, state => { this.submitLoading = state })
      if (res) {
        if (res.retData) {
          this.handleConfim(res.retData)
        } else {
          this.$message.success('提交成功')
          this.handleGoBack()
        }
      }
    },
    handleConfim (msg) {
      this.$confirm(`${msg}`, '提示', {
        type: 'warning',
      }).then(() => {
        this.submitAction('1')
      }).catch(() => {
        this.submitAction('0')
      });
    },
    // 上传之前
    handleBeforeUpload () {
      this.uploadLoading = true;
    },
    // 上传成功
    handleUploadSuccess (res) {
      this.uploadLoading = false;
      const { retMessage, retData } = res;
      if (isResponseSuccess(res)) {
        this.$message.success('导入成功');
        this.recordNo = retData;
        this.getTableData();
      } else {
        this.$message.error(retMessage || '导入失败');
      }
    },
    // 上传失败
    handleUploadError () {
      this.uploadLoading = false;
      this.$message.error('导入失败');
    },
    // 返回上一页
    handleGoBack () {
      this.$router.push({ name: 'limitAudit' });
    },
  }
}
</script>
<style lang="less" scoped>
.reson-form {
  width: 70%;
  /deep/.el-form-item {
    margin-bottom: 0;
  }
}
</style>
